package com.doumuxie.filter;

import com.alibaba.fastjson.JSON;
import com.doumuxie.dto.UserDto;
import com.doumuxie.utils.ResultUtil;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Configuration
public class AuthFilter implements Filter {

    private static Set<String> excludeUrl = new HashSet<>();

    static {
        excludeUrl.add("/");
        excludeUrl.add("/login");
        excludeUrl.add("/logout");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        servletResponse.setContentType("application/json;charset=UTF-8");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        String requestURI = httpServletRequest.getRequestURI();
        if (excludeUrl.contains(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpSession session = httpServletRequest.getSession();
        Object object = session.getAttribute(UserDto.USER_SESSION_KEY);
        if (object == null) {
            writeResponse(servletResponse, "请先登录");
            return;
        }
        UserDto userDto = (UserDto) object;
        if (userDto.getAuth().contains(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        writeResponse(servletResponse, userDto.getUsername() + "无权访问资源" + requestURI);


    }

    private void writeResponse(ServletResponse servletResponse, String msg) throws IOException {
        servletResponse.getWriter().write(JSON.toJSONString(ResultUtil.error(msg)));
    }


    @Override
    public void destroy() {

    }
}
